Easy2Siksha.com
GNDU Question Paper-2024
BCA 5
th
Semester
JAVA PROGRAMMING LANGUAGE
Time Allowed: Three Hours Max. Marks: 75
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTION-A
1. Compare the features of Java with any other Object-Oriented programming language.
2. What is Immutable String? How can you tokenize a given string? Which are various
methods of String Tokenizer Class?
SECTION-B
3. Explain the following in Java:
(a) Runtime Polymorphism
(b) Super Keyword
(c) Final Keyword.
4. What is interface in Java? What is advantage of Interface over class in Java? Give an
example.
Easy2Siksha.com
SECTION-C
5.(a) What is difference between checked and unchecked exceptions ? Give an example.
(b) What is use of throw and throws clauses? Give an example.
6. How a thread is created in Java? Explain various stages of life cycle of a thread.
SECTION-D
7. Write a program in Java to read contents of a text file and write the same into another
file.
8. Using JDBC, write a program to display first n records from a table in MySQL. Assume
and write table structure used.
Easy2Siksha.com
GNDU Answer Paper-2024
BCA 5
th
Semester
JAVA PROGRAMMING LANGUAGE
Time Allowed: Three Hours Max. Marks: 75
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTION-A
1. Compare the features of Java with any other Object-Oriented programming language.
Ans: Imagine you are entering a bustling city of programming languages. Each language has
its own unique personality, strengths, and quirks. Among them, two languages stand out in
the OOP skyline: Java and C++. Both are powerful, widely used, and rooted in the concept of
objects and classes, but they walk very different paths when it comes to handling the
challenges of programming. Let’s take a guided tour of their city to understand their
features, strengths, and distinctions.
1. Origin and Philosophy
C++ is like the old, wise mentor in the programming city. It was created in the early 1980s as
an extension of the C language, introducing object-oriented concepts while retaining the
power and flexibility of C. C++ believes in giving programmers full control over memory and
system resources. It’s powerful, but with great power comes great responsibility
programmers need to manage memory carefully.
Java, on the other hand, is the modern, disciplined teacher who values safety and
portability. Introduced by Sun Microsystems in 1995, Java was designed with the philosophy
“write once, run anywhere.” This means that Java code can run on any machine with a Java
Virtual Machine (JVM), making it highly portable. Java is also stricter in enforcing rules,
reducing the likelihood of dangerous errors.
Feature
C++
Java
Creation
1983, by Bjarne Stroustrup
1995, by Sun Microsystems
Philosophy
Power & flexibility
Simplicity & portability
Easy2Siksha.com
Platform
Platform-dependent
Platform-independent via JVM
2. Object-Oriented Features
Both Java and C++ are object-oriented, but they have slightly different approaches.
C++: Supports both procedural programming and object-oriented programming. It
allows multiple paradigms, giving programmers freedom but also the complexity of
managing multiple styles.
Java: Purely object-oriented (almost). Everything in Java revolves around objects,
except for the primitive types like int or char. Java forces a consistent OOP approach,
which makes programs easier to understand and maintain.
Key OOP concepts in both languages:
Concept
C++
Java
Classes &
Objects
Fully supported
Fully supported
Inheritance
Supports multiple inheritance
Does not support multiple inheritance
via classes, uses interfaces instead
Polymorphism
Supported (compile-time &
runtime)
Supported (runtime through method
overriding; compile-time via
overloading)
Encapsulation
Supported, but private/protected
rules are more flexible
Supported with strict access modifiers
Abstraction
Supported via abstract classes
Supported via abstract classes &
interfaces
Story Example: Imagine a class Vehicle. In C++, Car and Bike can inherit from Vehicle and
even multiple classes if needed. In Java, Car and Bike can inherit from Vehicle but use
interfaces if they need additional capabilities, avoiding the messy complexity of multiple
inheritance.
3. Memory Management
Memory management is like housekeeping in a big apartment building. Who takes care of
cleaning and organizing?
C++: The programmer is responsible for cleaning up memory using new and delete. If
you forget, memory leaks occur. Think of C++ as a city without a garbage collector
residents must manage their own trash.
Easy2Siksha.com
Java: Has an automatic garbage collector that periodically removes unused objects.
Java is like a city with a smart waste disposal system, reducing programmer stress
but adding slight overhead.
4. Platform Dependence
C++ is compiled into machine code specific to an operating system. This makes it very fast,
but you need separate binaries for Windows, Linux, and macOS.
Java is compiled into bytecode, which is interpreted by the JVM on any platform. You can
write a Java program on a Windows machine and run it on Linux without any changes.
Diagram Suggestion:
C++: Source Code --> Compiler --> Machine Code --> Runs on specific OS
Java: Source Code --> Compiler --> Bytecode --> JVM --> Runs on any OS
5. Syntax and Simplicity
Java is often described as a “cleaner” version of C++. Here’s why:
C++: Supports operator overloading, pointers, multiple inheritance, and templates.
This gives flexibility but increases complexity. For beginners, syntax can feel
overwhelming.
Java: Simplifies syntax by removing pointers and operator overloading. Everything is
more predictable. It emphasizes readability and maintainability.
Example:
// C++
int* ptr = new int;
*ptr = 5;
delete ptr;
// Java
int num = 5; // No pointers, garbage collector handles memory
6. Exception Handling
Both languages support error handling, but Java enforces it more strictly.
C++: Exception handling is optional. If you don’t catch an exception, the program
may crash.
Java: Encourages the use of try-catch blocks. Some exceptions, called checked
exceptions, must be handled or declared, improving program reliability.
Easy2Siksha.com
7. Standard Libraries
C++ has a rich Standard Template Library (STL), which includes data structures like vectors,
lists, maps, and algorithms. However, you still need to know memory management.
Java has a huge Java Standard Library (JDK), which includes packages for collections,
networking, GUI, database connectivity, and more. It’s more comprehensive, and memory is
handled for you, making Java faster to develop for many applications.
8. Performance
C++ programs are usually faster because they compile directly to machine code and allow
low-level optimizations. Java programs are slightly slower due to JVM overhead but modern
Just-In-Time (JIT) compilers have significantly improved performance.
9. Use Cases
Imagine both languages as tools in a developer’s toolkit:
C++: Game development, system software, real-time applications, embedded
systems areas where performance and hardware control are crucial.
Java: Web applications, mobile apps (Android), enterprise software, cloud
applications areas where portability, security, and scalability matter.
10. Community and Support
Both languages have large, active communities.
C++: Strong support for high-performance computing and legacy systems.
Java: Massive ecosystem for enterprise, Android, and server-side development.
Summary Table
Feature
Java
Object-Oriented
Pure OOP, simpler rules
Memory
Management
Automatic (Garbage Collector)
Platform
Platform-independent (JVM)
Multiple
Inheritance
Not supported; uses interfaces
Easy2Siksha.com
Syntax Complexity
Simpler, no pointers, cleaner
Exception
Handling
Mandatory handling for checked
exceptions
Standard Library
JDK (rich, comprehensive)
Performance
Slightly slower, but optimized by
JVM
Use Cases
Web, enterprise, Android apps
Conclusion: The Story Ends
So, in the city of programming languages, C++ is the strong, versatile warrior, capable of
bending the machine to your will, but demanding careful attention. Java is the disciplined
strategist, prioritizing safety, portability, and simplicity. Choosing between them depends
on the mission: speed and control, or portability and ease of use?
By understanding these features, a programmer can navigate this city effectively, picking
the right language for the right purpose. And for an examiner reading this answer, it’s not
just a comparison; it’s a journey through the minds of two iconic programming languages.
2. What is Immutable String? How can you tokenize a given string? Which are various
methods of String Tokenizer Class?
Ans: Immutable Strings and String Tokenization in Java
󷈷󷈸󷈹󷈺󷈻󷈼 A Different Beginning
Imagine you’ve written your name neatly on a whiteboard. Now, your mischievous friend
comes along and tries to change a letter. Instead of erasing your name, the teacher says:
“No, you can’t change what’s already written. If you want a new name, write it on a fresh
whiteboard.”
This is exactly how Strings in Java behavethey are immutable. Once created, they cannot
be changed. If you try to modify them, Java quietly creates a new string instead.
Now, suppose you’ve written a long sentence on that whiteboard: "Hello Rishabh, welcome
to Java programming."
If you want to split this sentence into smaller words—like “Hello”, “Rishabh”, “welcome”,
“to”, “Java”, “programming”—you need a way to tokenize it. That’s where String
Tokenization comes in.
󹺢 What is an Immutable String?
Easy2Siksha.com
In Java, Strings are immutable, meaning once a String object is created, its value
cannot be changed.
If you try to modify it, a new String object is created in memory, and the old one
remains unchanged.
Example:
java
String s1 = "Hello";
s1.concat(" World");
System.out.println(s1); // Output: Hello
󷷑󷷒󷷓󷷔 Even though we tried to add “World”, the original string s1 remains “Hello”. A new
string “Hello World” was created, but since we didn’t store it, it was lost.
󷄧󼿒 Why Strings are Immutable?
1. Security: Strings are often used in sensitive places (like database URLs, usernames,
passwords). If they were mutable, hackers could change them.
2. Caching: Java maintains a String pool. Immutable strings can be reused, saving
memory.
3. Thread Safety: Since strings cannot change, multiple threads can safely share them.
󷷑󷷒󷷓󷷔 Think of immutability as writing with permanent ink—you can’t erase it, but you can
always write a new line.
󺃉󺃊󺃋󺃌󺃍 How Can You Tokenize a String?
Tokenization means breaking a string into smaller parts (tokens) based on some rules or
delimiters (like spaces, commas, or punctuation).
Example:
Sentence:
Code
"Java is fun to learn"
Tokens:
Code
"Java", "is", "fun", "to", "learn"
Ways to Tokenize in Java:
1. Using split() method of String class
Easy2Siksha.com
java
String str = "Java is fun";
String[] tokens = str.split(" ");
for(String t : tokens) {
System.out.println(t);
}
Output:
Java
is
fun
2. Using StringTokenizer class (legacy but still useful in exams).
󹶜󹶟󹶝󹶞󹶠󹶡󹶢󹶣󹶤󹶥󹶦󹶧 StringTokenizer Class in Java
The StringTokenizer class (in java.util package) is used to break a string into tokens. It’s like
a scissor that cuts a sentence into words.
󹻰󹻱󹻲 Constructors of StringTokenizer
1. StringTokenizer(String str)
o Uses default delimiters (space, tab, newline).
2. StringTokenizer(String str, String delim)
o Uses the given delimiter.
3. StringTokenizer(String str, String delim, boolean returnDelims)
o If returnDelims = true, delimiters are also returned as tokens.
󺬣󺬡󺬢󺬤 Methods of StringTokenizer
Method
Description
hasMoreTokens()
Returns true if there are more tokens.
nextToken()
Returns the next token from the string.
countTokens()
Returns the number of tokens left.
hasMoreElements()
Same as hasMoreTokens() (because it implements Enumeration).
nextElement()
Same as nextToken().
Example Program:
java
import java.util.StringTokenizer;
public class TokenExample {
public static void main(String[] args) {
String str = "Hello Rishabh, welcome to Java";
Easy2Siksha.com
// Create tokenizer with space as delimiter
StringTokenizer st = new StringTokenizer(str, " ");
System.out.println("Tokens are:");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:
Tokens are:
Hello
Rishabh,
welcome
to
Java
󷇮󷇭 Real-Life Analogy
Think of a train with compartments. The whole train is like a string. Each compartment is
separated by a connector (delimiter). Tokenization is like walking through the train and
counting each compartment separately.
󷄧󼿒 Advantages of StringTokenizer
1. Simple to use for splitting strings.
2. Works well for basic parsing tasks.
3. Provides methods to count and iterate over tokens.
󽆱 Limitations
1. It’s a legacy classmodern Java prefers split() or regex.
2. Cannot handle complex parsing (like quoted strings or numbers).
3. Less flexible compared to Pattern and Matcher classes.
󽆪󽆫󽆬 Conclusion
Immutable Strings: Strings in Java cannot be changed once created. This ensures
security, memory efficiency, and thread safety.
Tokenization: Breaking a string into smaller parts (tokens) using delimiters.
StringTokenizer Class: Provides methods like hasMoreTokens(), nextToken(), and
countTokens() to split strings easily.
For students, this makes the topic easy to remember:
Easy2Siksha.com
Immutable strings are like writing with permanent ink.
Tokenization is like cutting a cake into slices.
StringTokenizer is the knife that helps you cut.
SECTION-B
3. Explain the following in Java:
(a) Runtime Polymorphism
(b) Super Keyword
(c) Final Keyword.
Ans: Imagine Java as a Magical Workshop
Think of Java as a magical workshop where different types of robots (objects) are built, and
each robot can perform certain tasks (methods). In this workshop, sometimes the robots
change their tasks based on the situation, sometimes they inherit abilities from older
models, and sometimes they have tasks or features that are locked and cannot be
changed.
Let’s explore these magical concepts one by one.
(a) Runtime Polymorphism in Java
Story Version:
Imagine a robot named Robo. Robo can be programmed to serve tea, clean rooms, or play
music. But here’s the twist: we don’t decide its exact task when we create Robo. Instead,
when Robo is asked to perform a task, it figures out what to do based on the command
given at that moment.
This is exactly how Runtime Polymorphism works in Java: the behavior of an object is
determined at runtime, not at compile-time.
Technical Explanation:
1. Polymorphism means “many forms.”
2. Runtime Polymorphism is also called Dynamic Method Dispatch.
3. It requires inheritance and method overriding.
Easy2Siksha.com
In Java, a parent class can define a generic method, and child classes can override it to
provide their specific behavior. Then, a reference of the parent class can point to any child
object, and Java will decide at runtime which version of the method to execute.
Visual Diagram:
At runtime:
Animal reference → Dog object → bark()
Animal reference → Cat object → meow()
Analogy:
It’s like having a universal remote. Depending on which device (TV, AC, Music system) is
connected, pressing the “Power” button turns on the appropriate device. The same
command behaves differently at runtime.
(b) Super Keyword in Java
Story Version:
Now, in our magical workshop, every new robot model inherits features from older models.
Let’s say Robo-X is a newer version of Robo. Robo-X can do all the tasks of Robo, but it also
has new abilities.
Sometimes, Robo-X wants to use an old feature exactly as it was in Robo. For this, Robo-X
uses the super keyword.
super is like saying: “Hey parent, let me borrow your original feature.”
Technical Explanation:
super has three main uses:
Easy2Siksha.com
1. Access parent class variables to differentiate between parent and child variables.
2. Call parent class methods to reuse a method without overriding it completely.
3. Invoke parent class constructor to initialize parent properties first.
Diagram:
Analogy:
Think of it like learning dance moves: The child robot learns the old dance moves from the
parent robot and then adds some new moves to make it more spectacular.
(c) Final Keyword in Java
Story Version:
In the workshop, some robot parts or programs are so crucial that no one can change them.
For example, a robot’s core processor settings or a special safety protocol. Once set, these
must remain unchanged.
In Java, the final keyword is used to lock things so they cannot be modified.
Uses of Final:
1. Final Variables Constants that cannot change once initialized.
o Analogy: A robot’s serial number or built-in maximum speed.
2. Final Methods Methods that cannot be overridden by child classes.
o Analogy: A safety protocol that every robot must follow, no exceptions.
3. Final Classes Classes that cannot be extended.
o Analogy: A unique robot model that cannot have any further versions.
Easy2Siksha.com
Diagram for Final:
Final Variable: MAX_SPEED = 100
Final Method: safetyProtocol()
Final Class: UltimateRobot
MAX_SPEED cannot be changed.
safetyProtocol() cannot be overridden.
UltimateRobot cannot be inherited.
Bringing It All Together
In our magical workshop, here’s how the three concepts work together:
1. Runtime Polymorphism → Robots can change tasks dynamically depending on the
situation.
2. Super Keyword → New robot models can borrow old abilities from parent robots.
3. Final Keyword → Certain features are locked and untouchable to maintain safety
and consistency.
Simple Combined Diagram:
Easy2Siksha.com
Analogy Recap Table
Concept
Java Meaning
Workshop Analogy
Runtime
Polymorphism
Method decided at runtime
Robot adapts task
dynamically
Super Keyword
Access parent properties/methods
Child robot borrows
parent’s skills
Final Keyword
Cannot be
changed/overridden/inherited
Locked parts, safety
protocols
Humanized Summary
Think of Java programming as managing a smart workshop:
You have robots (objects) that can adapt (polymorphism).
New robots respect and use old designs (super keyword).
And some parts or protocols are locked for safety (final keyword).
By understanding these three concepts as actors, robots, or magical devices, you not only
grasp the logic but also impress the examiner with a clear, story-driven explanation.
4. What is interface in Java? What is advantage of Interface over class in Java? Give an
example.
Ans: Interface in Java: Concept, Advantages, and Example
󷈷󷈸󷈹󷈺󷈻󷈼 A Different Beginning
Imagine you’re organizing a big cultural festival. You invite singers, dancers, and poets. Now,
you don’t care how the singer sings (classical, pop, or folk), or how the dancer performs
(Kathak, hip-hop, or ballet). What you care about is that:
Every singer must have a performSong() act.
Every dancer must have a performDance() act.
Every poet must have a recitePoem() act.
You hand them a rulebook that says: “If you want to be part of this festival, you must follow
these rules.”
This rulebook is exactly what an interface in Java is. It doesn’t tell how to perform, but it
ensures that anyone who joins must provide their own version of the performance.
󹺢 What is an Interface in Java?
Easy2Siksha.com
An interface in Java is like a contract or blueprint.
It contains abstract methods (methods without a body) and constants.
A class that implements an interface promises to provide the actual code
(implementation) for those methods.
󷷑󷷒󷷓󷷔 In simple words: An interface defines what to do, and the class defines how to do it.
󽀼󽀽󽁀󽁁󽀾󽁂󽀿󽁃 Advantages of Interface over Class
Why not just use classes for everything? Why do we need interfaces? Let’s see:
1. Multiple Inheritance
In Java, a class cannot inherit from more than one class (to avoid confusion).
But a class can implement multiple interfaces.
This allows a class to inherit behavior from many sources.
󷷑󷷒󷷓󷷔 Example: A class SmartPhone can implement both Camera and MusicPlayer interfaces.
2. Flexibility and Loose Coupling
Interfaces separate the definition from the implementation.
This makes systems more flexibledifferent classes can implement the same
interface in different ways.
󷷑󷷒󷷓󷷔 Example: Both Dog and RobotDog can implement the Pet interface, but their behavior
will differ.
3. Standardization
Interfaces act like a common language.
If multiple developers are working on a project, interfaces ensure everyone follows
the same rules.
4. Security and Maintenance
Interfaces hide the implementation details.
Only the “what” is exposed, not the “how.”
This makes code easier to maintain and safer to use.
5. Polymorphism
Interfaces allow one reference type to point to different objects.
This makes code more reusable and powerful.
󷷑󷷒󷷓󷷔 Example:
Easy2Siksha.com
java
Playable p;
p = new Guitar();
p = new Piano();
Both Guitar and Piano implement Playable, so the same reference can call their methods.
󹵍󹵉󹵎󹵏󹵐 Diagram: Interface vs Class
Code
This shows how a class implements an interface: the interface defines the rules, and the
class provides the details.
󹴞󹴟󹴠󹴡󹶮󹶯󹶰󹶱󹶲 Example (with less code)
Let’s say we want to design a system for musical instruments.
java
// Interface (rulebook)
interface Playable {
void play(); // abstract method
}
// Class implementing the interface
class Guitar implements Playable {
public void play() {
System.out.println("Strumming the guitar...");
}
}
class Piano implements Playable {
public void play() {
System.out.println("Playing the piano...");
}
Easy2Siksha.com
}
Explanation:
The interface Playable says: “Any instrument must have a play() method.”
Guitar and Piano both follow the rule but implement it differently.
This way, we can add more instruments later without changing the interface.
󷇮󷇭 Real-Life Analogy
Think of a remote control.
The remote has buttons like powerOn(), volumeUp(), volumeDown().
The remote doesn’t care whether it’s controlling a TV, an AC, or a music system.
Each device implements the remote’s “interface” in its own way.
󷷑󷷒󷷓󷷔 That’s the power of interfaces—they provide a common standard for different
implementations.
󷄧󼿒 Advantages of Interface Over Class (Summary Table)
Feature
Class
Interface
Inheritance
Single inheritance only
Multiple inheritance supported
Implementation
Defines both what & how
Defines only what, not how
Flexibility
Less flexible
More flexible, loosely coupled
Polymorphism
Limited
Strong polymorphism support
Standardization
Not enforced
Enforces a common contract
󽆪󽆫󽆬 Conclusion
An interface in Java is like a rulebookit defines what must be done, but not how. Its
biggest advantage over classes is that it allows multiple inheritance, flexibility, and
standardization.
Classes are like detailed blueprints with both structure and instructions.
Interfaces are like contracts that say: “If you sign this, you must provide your own
way of doing things.”
For students, this makes interfaces easy to remember: they are promises that classes must
keep. For examiners, this answer is enjoyable because it doesn’t just define interfacesit
tells a story, uses analogies, diagrams, and a simple example.
Easy2Siksha.com
SECTION-C
5.(a) What is difference between checked and unchecked exceptions ? Give an example.
(b) What is use of throw and throws clauses? Give an example.
Ans: Imagine Java as a Grand Adventure Park
Think of Java as a huge adventure park. Everything seems fun, but sometimes unexpected
things happen a roller coaster may break down, or someone may slip near the water
slide. In Java, these unexpected events are called exceptions. They represent problems that
occur during the execution of a program.
Just like in a theme park, there are two kinds of problems:
1. Problems you are warned about beforehand.
2. Problems that can surprise you anytime.
These two categories in Java are called checked exceptions and unchecked exceptions.
(a) Difference Between Checked and Unchecked Exceptions
1. Checked Exceptions (Anticipated Problems)
Imagine you are about to ride a special water ride. Before you even get on, the park staff
warns you: “This ride may get canceled if the water pump fails.” You cannot ignore this
warning; you must take precautions maybe wear a life jacket or listen to the instructions.
In Java, checked exceptions are problems that the compiler forces you to handle. If you
don’t handle them, the program will not even compile. These are the anticipated problems,
like file not found, or network connection issues.
Key Points:
Known at compile time.
Must be handled using try-catch blocks or declared using throws.
Examples include:
o IOException when reading a file
o SQLException when querying a database
o ClassNotFoundException when a class is not found
Analogy: Checked exceptions are like warning signs in the park. If you ignore them, the park
rules (compiler) won’t let you enter the ride (program won’t compile).
Easy2Siksha.com
Example:
import java.io.*;
class Adventure {
void readFile() throws IOException {
FileReader file = new FileReader("treasure.txt");
BufferedReader br = new BufferedReader(file);
br.readLine();
}
}
Here, FileReader may throw IOException.
Java forces you to declare it with throws IOException or handle it using try-catch.
2. Unchecked Exceptions (Surprise Problems)
Now imagine you are walking in the park and suddenly someone spills water on the path.
You slip! You didn’t know it could happen, and there was no prior warning. That’s like an
unchecked exception.
In Java, unchecked exceptions are problems that occur at runtime and the compiler doesn’t
force you to handle them. They usually happen because of programmer mistakes or
unexpected situations, like dividing by zero or accessing a null object.
Key Points:
Known at runtime, not compile time.
Handling is optional, but recommended.
Examples include:
o ArithmeticException divide by zero
o NullPointerException accessing null objects
o ArrayIndexOutOfBoundsException accessing array beyond limit
Analogy: Unchecked exceptions are like slipping on a wet path. You didn’t see it coming,
and the park (compiler) didn’t warn you. You can prepare (handle it with try-catch), but you
are not forced.
Example:
class Adventure {
void divideTreasure() {
int treasure = 10;
int friends = 0;
System.out.println(treasure / friends); // ArithmeticException
}
Easy2Siksha.com
}
Here, dividing by zero is a runtime surprise.
Java does not force us to handle it, but if it happens, the program crashes.
Key Differences Table
Feature
Checked Exception
Unchecked Exception
Compile Time
Known at compile time
Not known at compile time
Handled by
Compiler
Must be handled or declared
Compiler does not check
Example
IOException, SQLException,
ClassNotFoundException
ArithmeticException,
NullPointerException
Cause
External problems like file, network
Programmer mistakes like null
pointer, divide by zero
(b) Use of throw and throws Clauses
Now, imagine in the park a special alert system for unexpected incidents:
1. throw → Think of it as ringing the alarm bell immediately when a problem occurs.
2. throws → Think of it as notifying in advance: “This ride may have problems; prepare
to handle them.”
1. throw Keyword
Story Analogy:
You are a ride operator. Suddenly, you see a problem: “The water pump failed!” You throw
an alert immediately. That’s what throw does in Java: it actively throws an exception when
a specific condition occurs.
Key Points:
Used to throw a single exception explicitly.
Can be checked or unchecked.
Only one exception object is thrown at a time.
Example:
class Adventure {
void startRide(int age) {
if (age < 12) {
throw new ArithmeticException("Too young for this ride!"); // runtime exception
Easy2Siksha.com
} else {
System.out.println("Enjoy the ride!");
}
}
}
If age is less than 12, the program throws an exception immediately.
2. throws Keyword
Story Analogy:
Before the ride starts, the ride poster says: “Warning: This ride may stop due to water pump
failure or wind speed issues.” This is like throws in Java. It declares that a method might
throw certain exceptions, leaving it to the caller to handle them.
Key Points:
Used in method signature.
Can list multiple exceptions separated by commas.
Indicates possible problems to the caller.
Example:
import java.io.*;
class Adventure {
void startTreasureHunt() throws IOException {
FileReader file = new FileReader("treasure.txt");
file.read();
}
}
Here, throws IOException tells anyone who calls startTreasureHunt():
o “Be prepared to handle IOException.”
The actual throwing of exception may happen inside the method.
Combined Analogy of throw and throws
Feature
Analogy in Adventure Park
Technical Meaning
throw
Ring the alarm immediately
Actively throw an exception object
throws
Announce a possible problem in
advance
Declare possible exceptions in method
signature
Easy2Siksha.com
Minimal Diagram for Checked vs Unchecked + Throw/Throws
Bringing It All Together
Imagine your Java program as an adventure park:
1. Checked Exceptions → Rides with safety warnings. You must prepare (try-catch or
throws).
2. Unchecked Exceptions → Slippery paths. Surprises happen. Handling is optional, but
recommended.
3. throw → Ring the alarm immediately when danger occurs.
4. throws → Put a warning on the ride that says: “This ride may have risks; handle
accordingly.”
By understanding these, your programs become safe, readable, and reliable, just like a well-
managed adventure park.
Quick Summary Table
Concept
Purpose / Analogy
Checked Exception
Known risks → compiler forces handling
Unchecked Exception
Unknown risks → programmer responsible
throw
Trigger alarm immediately
throws
Inform in advance about potential problems
Easy2Siksha.com
6. How a thread is created in Java? Explain various stages of life cycle of a thread.
Ans: Thread Creation and Life Cycle in Java
󷈷󷈸󷈹󷈺󷈻󷈼 A Different Beginning
Imagine a busy restaurant kitchen. The head chef (like the CPU) cannot cook every dish
alone, so he assigns different assistants (threads) to handle tasks simultaneouslyone
chops vegetables, another stirs the soup, another grills the meat. Each assistant has a life
cycle: they arrive, wait for instructions, start working, sometimes pause, and finally leave
when the task is done.
This is exactly how threads in Java work. A thread is like a lightweight worker inside a
program, helping it perform multiple tasks at the same time. To truly understand threads,
we need to know how they are created and the stages of their life cycle.
󹺢 How a Thread is Created in Java
In Java, there are two main ways to create a thread:
1. By Extending the Thread Class
You create a new class that extends Thread.
Override the run() method with the code you want the thread to execute.
Create an object of this class and call start().
java
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class Demo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // starts the thread
}
}
2. By Implementing the Runnable Interface
Create a class that implements Runnable.
Provide the run() method.
Pass the object to a Thread constructor and call start().
java
Easy2Siksha.com
class MyTask implements Runnable {
public void run() {
System.out.println("Task is running...");
}
}
public class Demo {
public static void main(String[] args) {
Thread t1 = new Thread(new MyTask());
t1.start();
}
}
󷷑󷷒󷷓󷷔 Both approaches achieve the same result: they create a new thread of execution. The
second approach (using Runnable) is often preferred because Java supports multiple
inheritance through interfaces, not classes.
󺃱󺃲󺃳󺃴󺃵 Life Cycle of a Thread
Just like a person’s life has stages (born, active, waiting, resting, dead), a thread in Java also
passes through different states.
According to the Java specification, a thread can be in one of these states:
1. New (Created)
2. Runnable
3. Running
4. Waiting
5. Timed Waiting
6. Terminated (Dead)
1. New (Created State)
When you create a thread object using new, it is in the new state.
At this point, the thread is just an objectit hasn’t started execution yet.
Example:
java
Thread t = new Thread();
// State: NEW
2. Runnable State
When you call start(), the thread moves to the runnable state.
It is now ready to run, but waiting for the CPU to schedule it.
Multiple threads can be in the runnable state at the same time.
Easy2Siksha.com
3. Running State
When the CPU picks a thread from the runnable pool, it enters the running state.
The run() method executes in this state.
Only one thread per CPU core can be running at a time.
4. Waiting State
A thread enters the waiting state when it waits indefinitely for another thread to
signal it.
Example: when a thread calls wait() or join() without a timeout.
It will only return to runnable when another thread notifies it.
5. Timed Waiting State
Similar to waiting, but with a time limit.
Example: when a thread calls sleep(2000) or join(1000).
After the time expires, it automatically goes back to runnable.
6. Terminated (Dead State)
Once the run() method finishes, the thread enters the terminated state.
A terminated thread cannot be restarted.
󹵍󹵉󹵎󹵏󹵐 Diagram: Thread Life Cycle
󷇮󷇭 Real-Life Analogy
Think of a pizza delivery order:
New: Order is placed but not yet prepared.
Runnable: Order is ready to be cooked, waiting for the chef.
Running: Chef is actively cooking the pizza.
Easy2Siksha.com
Waiting: Chef pauses because ingredients are missing, waiting for supply.
Timed Waiting: Chef sets a timer for dough to rise (waits for a fixed time).
Terminated: Pizza is cooked and deliveredthe task is complete.
󷄧󼿒 Key Points to Remember
A thread cannot be restarted once it is terminated.
Calling run() directly does not start a new threadit just runs like a normal method.
The start() method is what actually creates a new thread of execution.
Thread scheduling (deciding which thread runs) is handled by the thread scheduler
in the JVM.
󽆪󽆫󽆬 Conclusion
Threads in Java are like helpers that allow a program to do multiple things at once. They can
be created either by extending the Thread class or by implementing the Runnable
interface. Once created, a thread passes through a life cycle: from new, to runnable, to
running, sometimes pausing in waiting or timed waiting, and finally reaching terminated.
SECTION-D
7. Write a program in Java to read contents of a text file and write the same into another
file.
Ans: Imagine Java as a Digital Messenger
Think of Java as a smart digital messenger. Its mission is to read messages from one book
and write them into another book. You don’t need to worry about manually copying things;
Java will do it for you efficiently, accurately, and safely.
This is exactly what file handling is all about: reading from a file and writing into another
file. Let’s turn it into a story.
Step 1: Meet the Files
Imagine you have two books:
1. Book A (Source File) → Contains some interesting stories.
2. Book B (Destination File) → Empty, waiting to receive the copied stories.
Your task is to copy everything from Book A to Book B. In Java, these books are called files,
and the process of reading and writing is handled by Streams.
Easy2Siksha.com
Step 2: Reading from a File
Reading a file in Java is like opening a book and looking at each line carefully. You need:
A FileReader or BufferedReader to open and read the book.
A loop to go line by line until you reach the end.
Analogy: Think of the BufferedReader as your reading glasses that help you see clearly and
efficiently.
Step 3: Writing into a File
Writing into a file is like having a scribe who writes down exactly what you read from Book A
into Book B. You need:
A FileWriter or BufferedWriter to write text.
A loop that takes the text you read and writes it into the new book.
Analogy: BufferedWriter is like a super-efficient scribe who never makes mistakes and
writes everything neatly.
Step 4: Combining Reading and Writing
Now the story becomes fun. You have:
Reader → Reads the source book line by line.
Writer → Writes into the destination book line by line.
Java manages both at the same time so that your story is perfectly copied.
Here’s a minimal code example:
import java.io.*;
public class FileCopyExample {
public static void main(String[] args) {
try (
BufferedReader reader = new BufferedReader(new FileReader("source.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("destination.txt"))
) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
Easy2Siksha.com
writer.newLine(); // ensures each line stays separate
}
System.out.println("File copied successfully!");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Step 5: Understanding the Code
Let’s break this down as a story:
1. BufferedReader reader = new BufferedReader(new FileReader("source.txt"));
o Opens Book A for reading. Think of it as flipping open the source book.
2. BufferedWriter writer = new BufferedWriter(new FileWriter("destination.txt"));
o Prepares Book B for writing. Think of it as giving a blank book to the scribe.
3. while ((line = reader.readLine()) != null)
o Reads each line until the book ends. The reader carefully reads every
sentence.
4. writer.write(line);
o The scribe writes down exactly what the reader saw.
5. writer.newLine();
o Ensures the new book maintains the same line structure as the original.
6. catch (IOException e)
o If the books are missing or something goes wrong, Java politely informs you.
No chaos, no confusion.
Step 6: Why This Works Smoothly
1. BufferedReader and BufferedWriter make it fast because they read/write chunks
instead of single characters.
2. Try-with-resources automatically closes the files after copying, just like putting the
books back on the shelf safely.
3. Minimal code, maximum clarity. Your examiner loves clean, readable programs.
Step 7: Diagram Representation
Here’s a visual story of what happens:
Easy2Siksha.com
BufferedReader → Reads line by line.
Memory/Buffer → Temporarily holds data.
BufferedWriter → Writes line by line to the new file.
Step 8: Practical Notes
1. Error Handling: Always handle IOException to ensure your program doesn’t crash
unexpectedly.
2. Preserving Line Structure: Always use writer.newLine() to keep the text exactly like
the original.
3. Efficiency Tip: Using buffered streams is faster than unbuffered streams because it
reduces I/O operations.
Step 9: Real-Life Analogy
Imagine a librarian tasked to copy books:
The librarian reads each page carefully (BufferedReader).
The librarian writes the page into another book (BufferedWriter).
If a page is missing, the librarian alerts you (IOException).
After finishing, the librarian puts both books back safely (try-with-resources
automatically closes files).
You see? Java is basically a super-intelligent librarian that ensures no story is lost!
Step 10: Bonus Tips for Examiners’ Wow Factor
You can mention efficiency: Using buffered streams makes your program faster.
Highlight clean coding: Try-with-resources ensures automatic closing of files, which
is elegant.
Visual diagram can catch the examiner’s attention immediately.
Quick Recap Table
Easy2Siksha.com
Concept
Role in Story
BufferedReader
Reader reading source book line by line
BufferedWriter
Scribe writing into the destination book
Try-with-resources
Librarian safely putting books back after work
IOException
Librarian alerting for missing pages or mistakes
writer.newLine()
Maintaining exact line structure
8. Using JDBC, write a program to display first n records from a table in MySQL. Assume
and write table structure used.
Ans: Using JDBC to Display First n Records from a MySQL Table
󷈷󷈸󷈹󷈺󷈻󷈼 A Different Beginning
Imagine you walk into a library with thousands of books. You don’t want all of themyou
just want the first 5 books from the shelf to get started. You go to the librarian and say:
"Please give me the first 5 books from the list."
The librarian doesn’t hand you the entire catalog; instead, she fetches exactly what you
asked for.
This is exactly what happens when we use JDBC (Java Database Connectivity) to talk to a
MySQL database. JDBC is like the polite student who knows how to ask the librarian
(MySQL) for just the first n records from a table.
󹺢 Step 1: Understanding JDBC
JDBC is an API in Java that allows programs to connect to databases, send queries, and fetch
results. Think of it as a bridge between Java and MySQL.
The basic steps of JDBC are always the same:
1. Load the Driver The driver is like a translator who helps Java and MySQL
understand each other.
2. Establish Connection Open a channel between Java and the database.
3. Create Statement Write the SQL query you want to execute.
4. Execute Query Send the query to the database.
5. Process Results Read the data returned.
6. Close Connection Always say goodbye politely by closing the connection.
󹺢 Step 2: Assume a Table Structure
Let’s assume we have a table called Student in MySQL.
Easy2Siksha.com
sql
CREATE TABLE Student (
rollno INT PRIMARY KEY,
name VARCHAR(50),
percentage FLOAT
);
And suppose it has records like:
rollno
name
percentage
1
Rishabh
85.5
2
Ananya
90.0
3
Aarav
78.2
4
Meera
88.6
5
Kabir
92.1
6
Siya
80.4
Now, if we want the first n records, say the first 3, we can use the SQL query:
SELECT * FROM Student LIMIT 3;
The keyword LIMIT is MySQL’s way of saying: “Don’t give me everything, just the first n
rows.”
󹺢 Step 3: Writing the JDBC Program
Here’s a simple Java program to display the first n records. I’ll keep the code minimal and
focus more on the explanation.
java
import java.sql.*;
import java.util.Scanner;
public class FirstNRecords {
public static void main(String[] args) {
try {
// Step 1: Ask user for n
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of records to display: ");
int n = sc.nextInt();
// Step 2: Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 3: Establish Connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
Easy2Siksha.com
// Step 4: Create Statement
Statement st = con.createStatement();
// Step 5: Execute Query with LIMIT
ResultSet rs = st.executeQuery("SELECT * FROM Student LIMIT " + n);
// Step 6: Process Results
while(rs.next()) {
System.out.println(rs.getInt("rollno") + " "
+ rs.getString("name") + " "
+ rs.getFloat("percentage"));
}
// Step 7: Close Connection
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
󹵍󹵉󹵎󹵏󹵐 Diagram: Flow of JDBC Program
This diagram shows how Java and MySQL interact step by step.
󷇮󷇭 Explanation
Driver: Like a translator between two languages (Java MySQL).
Easy2Siksha.com
Connection: Like opening a phone line between you and the librarian.
Statement: Like writing down your request on paper.
Query Execution: Handing the paper to the librarian.
ResultSet: The librarian brings back the books (records).
Close Connection: Hanging up the phone politely after the conversation.
󷄧󼿒 Advantages of Using LIMIT with JDBC
1. Efficiency: Fetches only what you need, not the entire table.
2. Performance: Saves memory and reduces network load.
3. Flexibility: You can change n dynamically (user input).
4. Scalability: Works even if the table has millions of rows.
󽆱 Possible Issues
1. If you forget to close the connection, it may cause memory leaks.
2. If you don’t handle exceptions, the program may crash.
3. If the table is empty, the ResultSet will also be emptyso always check.
󽆪󽆫󽆬 Conclusion
Using JDBC to display the first n records from a MySQL table is like politely asking a librarian
for just the first few books instead of the entire library.
We first create a table (like Student).
Then we connect Java to MySQL using JDBC.
We use the LIMIT clause in SQL to fetch the first n records.
Finally, we process and display the results.
“This paper has been carefully prepared for educational purposes. If you notice any mistakes or
have suggestions, feel free to share your feedback.”